extends Node


func change_scene(path: String, params := {}) -> void:
	# Available parameters:
	# - duration: the time used to let the scene fade in and out
	# - paused: pause the game if needed, default is `true`
	# - init: the action will be called before the scene changes
	# - entry_point: the name of an EntryPoint in the new scene
	# - position: the position where the player will be placed in the new scene
	# - is_new_game: it will disable the player entering animation to new 
	#				 EntryPoint, when its value is true
	# - entering_mode
	
	var duration := params.get("duration", 0.2) as float
	
	var tree := get_tree()
	tree.paused = params.get("paused", true) as bool
	
	if "init" in params: params.init.call()
	
	tree.change_scene_to_file(path)
	await  tree.tree_changed
	
	var direction := -1
	var is_entering := false
	var spawn_position := Vector2.ZERO
	if tree.current_scene is World:
		if "entry_point" in params:
			for node in tree.get_nodes_in_group("entry_point"):
				if node.name != params.entry_point: continue
				spawn_position = node.global_position
				is_entering = true
				break
		
		elif "position" in params:
			spawn_position = params.position
		
		if not params.get("is_new_game", false):
			var player = tree.get_first_node_in_group("player")
			player.direction = direction
			player.global_position = spawn_position
			player.is_entering = is_entering
			player.entering_mode = params.get("entering_mode")
			player.state_machine.current_state = player.states.ENTERING
	
	tree.paused = false


func get_player() -> Player:
	return get_tree().get_first_node_in_group("player")
